package com.cloud.sample.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.sample.dto.WebsocketMsgDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Websocket接口
 */
@Slf4j
@RestController
public class WebsocketController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 聊天
     *
     * @param msgDTO
     * @return ResultInfo
     */
    @MessageMapping("/chat")
    public ResultInfo<String> chat(WebsocketMsgDTO msgDTO) {
        log.info("chat msg: {}", msgDTO);
        return ResultInfo.success();
    }

    /**
     * 回复
     *
     * @param msgDTO
     * @return ResultInfo
     */
    @PostMapping("/reply")
    public ResultInfo<String> reply(WebsocketMsgDTO msgDTO) {
        log.info("reply msg: {}", msgDTO);
        messagingTemplate.convertAndSend("/" + msgDTO.getReceiverId(), msgDTO);
        return ResultInfo.success();
    }
}
